/******************************************************************************
 * Copyright (C) ShenZhen Powerdata Information Technology Co.,Ltd
 * All Rights Reserved.
 * 本软件为深圳市博安达信息技术股份有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、
 * 复制、修改或发布本软件.
 *****************************************************************************/

package com.szboanda.business.relevance.business.service.impl;

import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import com.szboanda.beijing.pure.BaseBusinessService;
import com.szboanda.business.relevance.business.dao.RelevanceBusinessDAO;
import com.szboanda.business.relevance.business.exception.RelevanceBusinessException;
import com.szboanda.business.relevance.business.service.IRelevanceBusinessService;
import com.szboanda.business.relevance.config.service.IRelevanceConfigService;
import com.szboanda.platform.common.component.datahelper.DataHelper;
import com.szboanda.platform.common.framext.mybatits.PlatformPageInfo;
import com.szboanda.platform.common.utils.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @title: 关联引擎关联关系组件_业务处理service实现类
 * @fileName: RelevanceBusinessServiceImpl.java
 * @description:
 * @copyright: PowerData Software Co.,Ltd. Rights Reserved.
 * @company: 深圳市博安达信息技术股份有限公司
 * @author: 原晋川
 * @date: 2019-09-21 18:35
 * @version: V1.0
 */
@Service("RelevanceBusinessService")
public class RelevanceBusinessServiceImpl extends BaseBusinessService implements IRelevanceBusinessService {

    /**
     * 注入业务处理DAO
     */
    @Autowired
    private RelevanceBusinessDAO relevanceBusinessDAO;

    /***
     * 注入关联引擎配置接口
     */
    @Autowired
    private IRelevanceConfigService relevanceConfigService;

    /**
     * 查询【关联引擎关联关系组件】业务信息
     *
     *
     * @param searchInfo 业务Map集合
     * @return 返回业务集合
     * @throws RelevanceBusinessException
     */
    @Override
    public List<Map<String, Object>> queryRelevanceBusinesss( Map<String, Object> searchInfo) throws RelevanceBusinessException {
        try {

            List<Map<String, Object>> list = relevanceBusinessDAO.queryRelevanceBusinesss(searchInfo);

            return list;
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "queryRelevanceBusinesss,an exception occured[searchInfo=" + searchInfo + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    @Override
    public List<Map<String, Object>> queryTaskListRelevanceBusinesss( Map<String, Object> searchInfo) throws RelevanceBusinessException {
        try {

            List<Map<String, Object>> list = relevanceBusinessDAO.queryTaskListRelevanceBusinesss(searchInfo);

            return list;
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "queryTaskListRelevanceBusinesss,an exception occured[searchInfo=" + searchInfo + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    /**
     * 单条查询
     *
     * @param xh 主键
     * @return
     * @throws RelevanceBusinessException
     */
    @Override
    public Map<String, Object> queryRelevanceBusinessByXh(String xh) throws RelevanceBusinessException {
        try {
            if (StringUtils.isEmpty(xh)) {
                return null;
            }
            Map<String, Object> searchInfo = new HashMap<String, Object>();
            searchInfo.put("XH", xh);
            Map<String, Object> model = relevanceBusinessDAO.queryRelevanceBusinessByXh(searchInfo);
            return model;

        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "queryRelevanceBusinessByXh,an exception occured[xh=" + xh + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    /**
     * 分页查询【关联引擎关联关系组件】业务信息
     *
     * @param pageNum    分页数
     * @param pageSize   分页长度
     * @param searchInfo 业务Map集合
     * @return 返回业务集合
     * @throws RelevanceBusinessException
     */
    @Override
    public PlatformPageInfo<Map<String, Object>> queryRelevanceBusinesssInPage(int pageNum, int pageSize, Map<String, Object> searchInfo) throws RelevanceBusinessException {
        try {
            DataHelper.startPage(pageNum, pageSize);
            // 排序处理
            List<Map<String, Object>> orders = (List<Map<String, Object>>) searchInfo.get("order");
            StringBuffer orderByStr = new StringBuffer();
            if (CollectionUtils.isNotEmpty(orders)) {
                for (Map<String, Object> order : orders) {
                    String field = MapUtils.getString(order, "field");
                    String direction = MapUtils.getString(order, "direction");
                    orderByStr.append(field).append(" ").append(direction);
                }
            }
            DataHelper.startPage(pageNum, pageSize, orderByStr.toString());
            List<Map<String, Object>> results = relevanceBusinessDAO.queryRelevanceBusinesss(searchInfo);
            return new PlatformPageInfo<Map<String, Object>>(results);

        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "查询关联引擎关联关系组件列表异常", e);
            throw new RelevanceBusinessException("查询关联引擎关联关系组件列表异常", e);
        }
    }

    /**
     * 保存【关联引擎关联关系组件】业务信息
     *
     * @param model 业务Map集合
     * @return 返回业务集合
     * @throws RelevanceBusinessException
     */
    @Override
    public Map<String, Object> saveRelevanceBusiness(Map<String, Object> model) throws RelevanceBusinessException {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = 0;
            super.createBaseInfo(model);
            if (isExist(model)) {
                count += relevanceBusinessDAO.updateRelevanceBusiness(model);
            } else {
                if ("".equals(MapUtils.getString(model, "XH_TEMP"))) {
                    model.put("XH", Toolkit.getID());
                } else {
                    model.put("XH", model.get("XH_TEMP"));
                }
                count += relevanceBusinessDAO.addRelevanceBusiness(model);
            }
            result.put("count",count);
            return result;
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "saveRelevanceBusiness,an exception occured[model=" + model + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    /**
     * 删除【关联引擎关联关系组件】业务信息
     *
     * @param infos 业务Map集合
     * @return 返回操作标识符
     * @throws RelevanceBusinessException
     */
    @SuppressWarnings("unchecked")
    @Override
    public int deleteRelevanceBusiness(Map<String, Object> infos) throws RelevanceBusinessException {
        try {
           /* List<String> delXhs = new ArrayList<String>();
            List<Map<String, Object>> modelInfos = (List<Map<String, Object>>) infos.get("models");
            for (Map<String, Object> modelInfo : modelInfos) {

                delXhs.add(MapUtils.getString(modelInfo, "XH"));
            }
//            NamedQueryHelper
            Map<String, Object> info = new HashMap<String, Object>();
            info.put("delXHs", delXhs);*/
            int count = relevanceBusinessDAO.deleteRelevanceBusinessByXhs(infos);
            return count;
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "deleteRelevanceBusiness,an exception occured[infos=" + infos + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    /**
     * 按主键删除【关联引擎关联关系组件】业务信息
     *
     * @param xh 主键
     * @return 返回操作标识符
     * @throws RelevanceBusinessException
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> deleteRelevanceBusinessByXh(String xh) throws RelevanceBusinessException {
        try {
            return new HashMap<>();
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), "deleteRelevanceBusinessByXh,an exception occured[xh=" + xh + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    /**
     * 功能描述: 根据配置查询数据
     *
     *
     * @param pageNum
     * @param pageSize
     * @param  params 参数类型
     * @return
     * @throws
     * @auther 原晋川
     * @date 2019/9/23 10:17
     */
    @Override
    public PlatformPageInfo<Map<String, Object>> queryListByConfig(int pageNum, int pageSize, Map<String, Object> params) throws RelevanceBusinessException {

        //由于是动态sql查询多个表，所以不能用封装的分页组件，
        try {
            DataHelper.startPage(pageNum, pageSize);
            // 排序处理
            List<Map<String, Object>> orders = (List<Map<String, Object>>) params.get("order");
            StringBuffer orderByStr = new StringBuffer();
            if (CollectionUtils.isNotEmpty(orders)) {
                for (Map<String, Object> order : orders) {
                    String field = MapUtils.getString(order, "field");
                    String direction = MapUtils.getString(order, "direction");
                    orderByStr.append(field).append(" ").append(direction);
                }
            }
            String type = MapUtils.getString(params, "type");
            String keyWords = MapUtils.getString(params, "KEY_WORD");

            List<String> BMLIST = (List<String>)params.get("BMLIST");
            String bmstr = Joiner.on("','").join(BMLIST);
            //type为多个流程时
            String[] strArr = type.split(",");
            //定义个sql
            StringBuffer sqlBuffer = new StringBuffer();
            for(int i = 0;i < strArr.length;i++){
                if(i!=0){
                    sqlBuffer.append(" union all ") ;
                }
                Map<String, Object> model = new HashMap<>();
                model.put("YWLXMC", strArr[i]);
                List<Map<String, Object>> configs = relevanceConfigService.queryRelevanceConfigs(model);
                model = configs.get(0);
                String sql = MapUtils.getString(model, "GLLBSQL");

                String bt="";

                if(!isNull(keyWords)){
                    if(strArr[i].equals("FW")||strArr[i].equals("QB")||strArr[i].equals("YY")||strArr[i].equals("WS")){
                        bt = "BT";
                    }else if(strArr[i].equals("LW")){
                        bt = "LWBT";
                    }
                    sql += " AND "+bt +" like '%"+keyWords+"%'";
                }

                if(StringUtils.isNotEmpty(bmstr)){
                    if(strArr[i].equals("LW")){
                        sql += " and SWDJBM in ('"+bmstr+"') ";
                    }else{
                        sql += " and ngbm in ('"+bmstr+"') ";
                    }

                }
                sqlBuffer.append(sql);
            }
            DataHelper.startPage(pageNum, pageSize, orderByStr.toString());
            List<Map<String, Object>> flowList = relevanceBusinessDAO.queryDataBySql(sqlBuffer.toString());
            PlatformPageInfo<Map<String, Object>> flowListsPage =  new PlatformPageInfo<Map<String, Object>>(flowList);
            return flowListsPage;
        } catch (RelevanceBusinessException e) {
            LoggerUtil.error(this.getClass(), "queryListByConfig,an exception occured[params=" + params + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    /**判断字符串是否为空
     * @param str
     * @return true:字符串为空
     * false:不为空
     */
    private static boolean isNull(String str) {
        boolean result = false;
        if (str != null && !"".equals(str) && !"null".equalsIgnoreCase(str) && !"NaN".equalsIgnoreCase(str)  && !"undefined".equalsIgnoreCase(str)) {
            result = false;
        } else {
            result = true;
        }
        return result;
    }


    @Override
    public PageInfo<Map<String, Object>> queryTaskListByConfig(int pageNum, int pageSize, Map<String, Object> params) throws RelevanceBusinessException {
        //由于是动态sql查询多个表，所以不能用封装的分页组件，
        try {
            params.put("CBR", this.getCurrUser().getYhid());
            DataHelper.startPage(pageNum, pageSize);
            // 排序处理
            List<Map<String, Object>> orders = (List<Map<String, Object>>) params.get("order");
            StringBuffer orderByStr = new StringBuffer();
            if (CollectionUtils.isNotEmpty(orders)) {
                for (Map<String, Object> order : orders) {
                    String field = MapUtils.getString(order, "field");
                    String direction = MapUtils.getString(order, "direction");
                    orderByStr.append(field).append(" ").append(direction);
                }
            }
            DataHelper.startPage(pageNum, pageSize, orderByStr.toString());
            List<Map<String, Object>> flowList = relevanceBusinessDAO.queryTaskListData(params);
            PlatformPageInfo<Map<String, Object>> flowListsPage =  new PlatformPageInfo<Map<String, Object>>(flowList);
            return flowListsPage;
        } catch (RelevanceBusinessException e) {
            LoggerUtil.error(this.getClass(), "queryTaskListByConfig,an exception occured[params=" + params + "]", e);
            throw new RelevanceBusinessException(e);
        }
    }

    private String shengChengBmtj(Map<String, Object> params){
        String sql = "";
        String BMBH = MapUtils.getString(params,"BMBH");
        if(StringUtils.isNotEmpty(BMBH)){
            sql +="";
        }

        return sql;
    }

    /**
     *
     * @param businessId
     * @return int
     * @author 袁云飞
     * @creed: //添加关联关系之前先删除之前添加的
     * @date 2019/12/6 20:33
     */
    @Override
    public int deleteRelevanceBusinessByBusinessId(String businessId) {
        int count = relevanceBusinessDAO.deleteRelevanceBusinessByBusinessId(businessId);
        return count;
    }

    /**
     * 判断【关联引擎关联关系组件】业务信息是否存在
     *
     * @param model 业务Map集合
     * @return 返回操作标识符
     * @throws RelevanceBusinessException
     */
    private boolean isExist(Map<String, Object> model) {

        return !"".equals(MapUtils.getString(model, "XH"));
    }


}
